import { defineStore } from 'pinia'
import { ref } from 'vue'
import orderApi from '@/api/OrdersApi.js';
import { ElMessage } from 'element-plus'

export const useOrderStore = defineStore('order', () => {
  const orders = ref([]) // 订单列表
  const currentOrder = ref(null) // 当前订单详情
  const pagedOrders = ref({}) // 分页订单数据
  const orderCounts = ref({ // 订单状态统计
    pendingPayment: 0,   // 待支付(状态1)
    pendingShipment: 0,  // 待发货(状态2)
    pendingReceipt: 0,   // 待收货(状态3)
    pendingReview: 0,    // 待评价(状态4)
    afterSale: 0         // 退款/售后(状态5)
  })
  const isLoading = ref(false) // 加载状态
  const error = ref(null) // 错误信息

  /**
   * 创建新订单
   * @param {Object} ordersDTO 订单数据
   * @returns {Promise} 包含订单信息的Promise
   */
  const createOrder = async (ordersDTO) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.createOrder(ordersDTO)

      if (response.code === 1) {
        ElMessage.success('订单创建成功')
        return response
      } else {
        throw new Error(response.msg || '订单创建失败')
      }
    } catch (err) {
      error.value = err.message || '订单创建失败'
      console.error('创建订单失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 根据用户ID和状态获取订单列表
   * @param {Number} userId 用户ID
   * @param {Number} [status] 订单状态(可选)
   * @returns {Promise} 包含订单列表的Promise
   */
  const fetchOrdersByUserAndStatus = async (userId, status) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.getOrdersByUserAndStatus(userId, status)

      if (response.code === 1) {
        orders.value = response.data || []
        return orders.value
      } else {
        throw new Error(response.msg || '获取订单列表失败')
      }
    } catch (err) {
      error.value = err.message || '获取订单列表失败'
      console.error('获取订单列表失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 分页查询订单
   * @param {Object} queryParams 查询参数
   * @returns {Promise} 包含分页订单数据的Promise
   */
  const fetchOrdersPaged = async (queryParams) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.getOrdersPaged(queryParams)

      if (response.code === 1) {
        pagedOrders.value = response.data || {}
        return pagedOrders.value
      } else {
        throw new Error(response.msg || '获取分页订单失败')
      }
    } catch (err) {
      error.value = err.message || '获取分页订单失败'
      console.error('获取分页订单失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取订单详情
   * @param {Number} orderId 订单ID
   * @returns {Promise} 包含订单详情的Promise
   */
  const fetchOrderDetail = async (orderId) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.getOrderDetail(orderId)

      if (response.code === 1) {
        currentOrder.value = response.data
        return currentOrder.value
      } else {
        throw new Error(response.msg || '获取订单详情失败')
      }
    } catch (err) {
      error.value = err.message || '获取订单详情失败'
      console.error('获取订单详情失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 取消订单
   * @param {Number} orderId 订单ID
   * @returns {Promise} 包含操作结果的Promise
   */
  const cancelOrder = async (orderId) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.cancelOrder(orderId)

      if (response.code === 1) {
        ElMessage.success('订单取消成功')
        // 更新本地订单状态
        const order = orders.value.find(o => o.orderId === orderId)
        if (order) {
          order.orderStatus = 0 // 0表示已取消
        }
        if (currentOrder.value?.orderId === orderId) {
          currentOrder.value.orderStatus = 0
        }
        return true
      } else {
        throw new Error(response.msg || '订单取消失败')
      }
    } catch (err) {
      error.value = err.message || '订单取消失败'
      console.error('取消订单失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 确认收货
   * @param {Number} orderId 订单ID
   * @returns {Promise} 包含操作结果的Promise
   */
  const confirmOrderReceipt = async (orderId) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.confirmReceipt(orderId)

      if (response.code === 1) {
        ElMessage.success('确认收货成功')
        // 更新本地订单状态
        const order = orders.value.find(o => o.orderId === orderId)
        if (order) {
          order.orderStatus = 4 // 4表示已签收
        }
        if (currentOrder.value?.orderId === orderId) {
          currentOrder.value.orderStatus = 4
        }
        return true
      } else {
        throw new Error(response.msg || '确认收货失败')
      }
    } catch (err) {
      error.value = err.message || '确认收货失败'
      console.error('确认收货失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 申请售后
   * @param {Number} orderId 订单ID
   * @param {String} reason 售后原因
   * @returns {Promise} 包含操作结果的Promise
   */
  const applyForAfterSale = async (orderId, reason) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.applyAfterSale(orderId, reason)

      if (response.code === 1) {
        ElMessage.success('售后申请已提交')
        // 更新本地订单状态
        const order = orders.value.find(o => o.orderId === orderId)
        if (order) {
          order.orderStatus = 6 // 6表示申请售后
        }
        if (currentOrder.value?.orderId === orderId) {
          currentOrder.value.orderStatus = 6
        }
        return true
      } else {
        throw new Error(response.msg || '售后申请失败')
      }
    } catch (err) {
      error.value = err.message || '售后申请失败'
      console.error('申请售后失败:', err)
      ElMessage.error(error.value)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取订单状态统计
   * @param {Number} userId 用户ID
   * @returns {Promise} 包含订单统计的Promise
   */
  const fetchOrderStatusCounts = async (userId) => {
    isLoading.value = true
    error.value = null
    try {
      const response = await orderApi.getOrderStatusCounts(userId)

      if (response.code === 1) {
        orderCounts.value = response.data || {
          pendingPayment: 0,
          pendingShipment: 0,
          pendingReceipt: 0,
          pendingReview: 0,
          afterSale: 0
        }
        return orderCounts.value
      } else {
        throw new Error(response.msg || '获取订单统计失败')
      }
    } catch (err) {
      error.value = err.message || '获取订单统计失败'
      console.error('获取订单统计失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 清除当前订单详情
   */
  const clearCurrentOrder = () => {
    currentOrder.value = null
  }

  /**
   * 清除所有订单数据
   */
  const clearAllOrders = () => {
    orders.value = []
    currentOrder.value = null
    pagedOrders.value = {}
    orderCounts.value = {
      pendingPayment: 0,
      pendingShipment: 0,
      pendingReceipt: 0,
      pendingReview: 0,
      afterSale: 0
    }
    error.value = null
  }

  return {
    orders,
    currentOrder,
    pagedOrders,
    orderCounts,
    isLoading,
    error,

    createOrder,
    fetchOrdersByUserAndStatus,
    fetchOrdersPaged,
    fetchOrderDetail,
    fetchOrderStatusCounts,
    cancelOrder,
    confirmOrderReceipt,
    applyForAfterSale,
    clearCurrentOrder,
    clearAllOrders
  }
})